package com.jmda.platform.repository.form.action;

import com.jmda.platform.commom.ResourcePathConfig;
import com.jmda.platform.commom.util.FileUtil;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.application.model.ApplicationModel;
import com.jmda.platform.repository.application.service.ApplicationSevice;
import com.jmda.platform.repository.form.model.FormMetadataMapModel;
import com.jmda.platform.repository.form.model.FormMetadataModel;
import com.jmda.platform.repository.form.model.FormModel;
import com.jmda.platform.repository.form.service.FormMetadataService;
import com.jmda.platform.repository.form.service.FormService;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/repository/form/templete")
public class FormTempleteController {
    @Resource
    FormService formServer;
    @Resource
    ResourcePathConfig resourceLoaderPath;
    @Resource
    FormMetadataService formMetadataService;
    @Resource
    FreeMarkerConfigurer freeMarkerConfigurer;

    @RequestMapping(value = "/getTempletePage", method = {RequestMethod.POST, RequestMethod.GET})
    public String getFormBasePage(String formId, HttpServletRequest request, ModelMap map) throws ResositoryException, IOException, TemplateException {
        FormModel model = formServer.get(formId);
        //String eformPath = resourceLoaderPath.getTemplateEformPath();
        ApplicationModel appModel = applicationSevice.get(model.getApplication_id());
        String eformPath = resourceLoaderPath.getTemplateEformPath() + appModel.getXieyin_code() + File.separator;
        String templateName = model.getTemplete_name() == null ? "" : model.getTemplete_name();
        String eformFileRealPath = eformPath + templateName;
        if (templateName.equals("")) {
            eformFileRealPath = eformFileRealPath + "sys_fail_null.ftl";
            map.put("ftlHtml", "表单模板为空,请点击“套用模版”功能");
        }
        File file = new File(eformFileRealPath);
        if (file.exists()) {
            String fltHtml = FileUtil.readAll(eformFileRealPath);
            Template eformMetaTemplete = freeMarkerConfigurer.getConfiguration().getTemplate("comm/eformMetaDebug.ftl");
            Map<String, Object> tmpMap = new HashMap<String, Object>();
            tmpMap.put("basePath", request.getContextPath());
            String eformMetaHtml = FreeMarkerTemplateUtils.processTemplateIntoString(eformMetaTemplete, tmpMap);
            fltHtml = fltHtml.replaceAll("<!--公共资源配置开始-->[\\s\\S]*?<!--公共资源配置结束-->", "<!--公共资源配置开始-->" + eformMetaHtml + "<!--公共资源配置结束-->");
            map.put("ftlHtml", fltHtml);
        }
        File templateFile = new File(eformPath);
        File[] list = templateFile.listFiles();
        /* 此处获取文件夹下的所有文件 */
        StringBuffer templatePageJson = new StringBuffer();
        templatePageJson.append("<select id='templatePage' name='templatePage' onchange='applyTemplate();' style='width:300px;height:22px;'>");
        Boolean isExit = false;
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                String tempName = list[i].getName();
                if (tempName.endsWith(".ftl")) {
                    templatePageJson.append("<option value='").append(tempName).append("' ");
                    if (tempName.equals(templateName)) {
                        templatePageJson.append("selected");
                        isExit = true;
                    }
                    templatePageJson.append(">").append(tempName).append("</option>");
                }
            }
        }

        if (!isExit) {
            templatePageJson.append("<option value='").append(model.getTemplete_name()).append("' selected >").append(model.getTemplete_name()).append("</option>");
        }
        templatePageJson.append("</select>");
        StringBuffer tdJson = new StringBuffer();
        tdJson.append("<select id='tdStyleSelect' name='tdStyleSelect'  style='width:300px;height:22px;'>");
        tdJson.append("<option value='col-sm-10'>一列</option>");
        tdJson.append("<option value='col-sm-6'>二列</option>");
        tdJson.append("<option value='col-sm-4'>三列</option>");
        tdJson.append("<option value='col-sm-3' selected>四列</option>");
        tdJson.append("<option value='col-sm-3_2'>四列_2</option>");
        tdJson.append("<option value='col-sm-3_3'>四列_3</option>");
        tdJson.append("<option value='col-sm-2'>五列</option>");
        tdJson.append("</select>");
        map.put("templatePage", templatePageJson.toString());
        map.put("templateName", model.getTemplete_name());
        map.put("formId", formId);
        map.put("tdJson", tdJson);
        return "repository/form/Sys_Repository_Form_Template";
    }

    @Resource
    ApplicationSevice applicationSevice;

    @RequestMapping(value = "/createDefaultTemplete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String createDefaultTemplete(String formId, String tdStyleValue) throws ResositoryException {

        FormModel formModel = formServer.get(formId);
        String form_name = formModel.getName();
        FormMetadataModel master = formMetadataService.getMasterFormMetadataModel(formId);
        ApplicationModel appModel = applicationSevice.get(formModel.getApplication_id());
        Map<String, Object> tmpMap = new HashMap<String, Object>();
        tmpMap.put("divTdStyle", tdStyleValue);
        if (master != null) {
            List<FormMetadataMapModel> mainFormMetadataMaps = master.getFormMetadataMapList();
            List<FormMetadataMapModel> oneFormMetadataMaps = new ArrayList<>();
            List<FormMetadataMapModel> listFormMetadataMaps = new ArrayList<>();
            if (mainFormMetadataMaps != null && mainFormMetadataMaps.size() > 0) {
                for (FormMetadataMapModel formMetadataMapModel : mainFormMetadataMaps) {
                    String type = formMetadataMapModel.getUi_type();
                    if (type != null && type.equals("多行")) {
                        oneFormMetadataMaps.add(formMetadataMapModel);
                    } else {
                        listFormMetadataMaps.add(formMetadataMapModel);
                    }
                }
                tmpMap.put("mainFormMetadataMapList", listFormMetadataMaps);
                tmpMap.put("oneFormMetadataMapList", oneFormMetadataMaps);
            }

            tmpMap.put("buttons", master.getFormMetadataButtonList());
            List<FormMetadataModel> subFormMetadataList = formMetadataService.getSubFormMetadataList(formId);
            tmpMap.put("subFormMetadataList", subFormMetadataList);
        }
        try {
            String eformPath = resourceLoaderPath.getTemplateEformPath() + appModel.getXieyin_code() + File.separator;
            String systemPath = resourceLoaderPath.getTemplateSystemPath();
            String url = systemPath + "sys_eform_easyui.ftl";
            tmpMap.put("form_name", form_name);
            tmpMap.put("extMeta", "${extMeta}");
            if (formModel.getWorkflowId() != null && !"".equals(formModel.getWorkflowId().trim())) {
                tmpMap.put("workflow", "${workflow}");
            }
            String templateName = "system/sys_eform_easyui.ftl";
            if (tdStyleValue != null && tdStyleValue.equals("col-sm-10")) {
                templateName = "system/sys_eform_easyui_one.ftl";
            } else if (tdStyleValue != null && tdStyleValue.equals("col-sm-6")) {
                templateName = "system/sys_eform_easyui_two.ftl";
            }else if (tdStyleValue != null && tdStyleValue.equals("col-sm-3_2")) {
                templateName = "system/sys_eform_easyui_2.ftl";
            }else if (tdStyleValue != null && tdStyleValue.equals("col-sm-3_3")) {
                templateName = "system/sys_eform_easyui_3.ftl";
            }
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            String str = FreeMarkerTemplateUtils.processTemplateIntoString(template, tmpMap);
            try {
                ClassPathResource cp = new ClassPathResource(url);
                //判断是否存在该文件
                cp.getURL().toString();
                File dirFoder = new File(eformPath);
                if (!dirFoder.isDirectory()) {
                    dirFoder.mkdirs();
                }
                StringBuffer formfileUrl = new StringBuffer();
                formfileUrl.append(eformPath).append("/").append(formModel.getXieyin_code()).append(".ftl");
                FileUtil.write(formfileUrl.toString(), str);
                formModel.setTemplete_name(formModel.getXieyin_code() + ".ftl");
                formServer.store(formModel);
            } catch (Exception e) {
                // TODO: handle exception
                return "noexist";
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "ok";
    }

    @RequestMapping(value = "/saveFormTemplete", method = {RequestMethod.POST})
    @ResponseBody
    public String saveFormTemplete(String formId, String templateName, String formHtml, HttpServletRequest request) {
        try {
            FormModel formModel = formServer.get(formId);
            ApplicationModel appModel = applicationSevice.get(formModel.getApplication_id());
            String eformPath = resourceLoaderPath.getTemplateEformPath() + appModel.getXieyin_code() + File.separator;
            String formfileUrl = eformPath + templateName;
            File formFile = new File(formfileUrl);
            if (formFile.exists()) {
                formHtml = formHtml.replaceAll("<!--公共资源配置开始-->[\\s\\S]*?<!--公共资源配置结束-->", "<!--公共资源配置开始--><#include \"../../comm/eformMeta.ftl\" /><!--公共资源配置结束-->");
                FileUtil.write(formfileUrl, formHtml);
            } else {
                return "noexist";
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ResositoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "ok";
    }

    @RequestMapping(value = "/applyFormTemplate", method = {RequestMethod.POST})
    @ResponseBody
    public String applyFormTemplate(String formId, String newTemplatePage) throws ResositoryException {
        FormModel formModel = formServer.get(formId);
        formModel.setTemplete_name(newTemplatePage);
        formServer.store(formModel);
        return "ok";
    }
}
